using System;
using System.Collections.Generic;
using System.Linq;
using Project.Models.Abstractions;

namespace Project.Models
{
    public class WorldInventory : Inventory
    {
        private readonly HashSet<IReadOnlyInventory> _inventories;

        public WorldInventory(ItemConfigsStorage itemConfigsStorage) : base(1, int.MaxValue, 1, itemConfigsStorage)
        {
            _inventories = new HashSet<IReadOnlyInventory>();
        }

        public void RegisterInventory(IReadOnlyInventory inventory)
        {
            _inventories.Add(inventory);

            inventory.ItemsLost += OnItemsLost;
        }

        public override void Dispose()
        {
            base.Dispose();

            foreach (var inventory in _inventories)
                inventory.ItemsLost -= OnItemsLost;
        }

        private void OnItemsLost(int itemId, int remainingQuantityOfItems)
        {
            if (remainingQuantityOfItems > 0)
            {
                this.AddItems(itemId, remainingQuantityOfItems);

                if (!this.Slots.Any(slot => slot.IsEmpty.Value))
                    this.AddSlotToEnd();
            }
        }
    }
}
